package com.sdlogan.pbudget;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
 * Class that communicates with external web service to backup personal data
 * @author Sean
 *
 */
public class Export extends Activity {
	Intent myIntent;
	public TextView tv;
	MoneyTable mt;
	List<dbPackage> values;
	EditText email;
	EditText pword;
	String loginemail;
	String loginpword;
	
	
	/**
	 * Initialize the xml and xml elements
	 */
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.export);
        mt = new MoneyTable(this);
        mt.open();
        values = mt.getAllRows();
        mt.close();
        Handler toastHandler = new Handler();
        email = (EditText) findViewById(R.id.exportemail);
        pword = (EditText) findViewById(R.id.exportpassword);
        Button export = (Button) findViewById(R.id.exportbutton);
        export.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				loginemail = email.getText().toString().trim();
				loginpword = pword.getText().toString().trim();
				Thread cThread = new Thread(new ClientUploadThread(values,loginemail,loginpword,Export.this));
				cThread.start();

			}
		});
        Button imported = (Button) findViewById(R.id.importdata);
        imported.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				loginemail = email.getText().toString();
				loginpword = pword.getText().toString();
				//Thread cThread = new Thread(new ClientImportThread());
				//cThread.start();
				
			}
		});
        
    }
	/**
	 * Inflate the options menu
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
}
	/**
	 * Handle options selected in menu
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.home:
			Log.i("Sean","Pressed Home");
			myIntent = new Intent(Export.this, Main.class);
			startActivityForResult(myIntent,0);
			return true;
		case R.id.graphs:
			return true;
		case R.id.incomechart:
			Log.i("Sean","income Graph");
			myIntent = new Intent(Export.this,Graphs.class);
			myIntent.putExtra("type","Income");
			startActivityForResult(myIntent,0);
			return true;
		case R.id.expensechart:
			Log.i("Sean","expense graph");
			myIntent = new Intent(Export.this,Graphs.class);
			myIntent.putExtra("type","Expense");
			startActivityForResult(myIntent,0);
			return true;
		case R.id.incomes:
			Log.i("Sean","Pressed Result");
			myIntent = new Intent(Export.this, Incomes.class);
			startActivityForResult(myIntent,0);
			return true;
		case R.id.expenses:
			Log.i("Sean","Pressed Expense");
			myIntent = new Intent(Export.this,Expenses.class);
			startActivityForResult(myIntent,0);
			return true;
		case R.id.export:
			Log.i("Sean","Pressed Export");
			myIntent = new Intent(Export.this, Export.class);
			startActivityForResult(myIntent,0);
			return true;
		case R.id.newvalue:
			Log.i("Sean","Pressed New");
			return true;
		case R.id.incomenew:
			Log.i("Sean","Pressed Income");
			myIntent = new Intent(Export.this,SubmitForm.class);
			myIntent.putExtra("type","Income");
			startActivityForResult(myIntent,0);
			return true;
		case R.id.expensenew:
			Log.i("Sean","Pressed Expense");
			myIntent = new Intent(Export.this,SubmitForm.class);
			myIntent.putExtra("type","Expense");
			startActivityForResult(myIntent,0);
			return true;
		default: 
			return false;
		}
		
	}
}
 /**
  * Class that handles uploading backs up external server
  * @author Sean
  *
  */
class ClientUploadThread implements Runnable {
	List<dbPackage> values;
	Iterator it;
	String email;
	String pword;
	Activity ac;
	/**
	 * Constructor
	 * @param inputs : All values found in the database
	 * @param e      : Login Email
	 * @param p      : Login Password
	 */
	public ClientUploadThread(List<dbPackage> inputs,String e,String p,Activity ac) {
		this.values = inputs;
		this.email = e;
		this.pword = p;
		this.ac = ac;
	}

	/**
	 * Run method in thread that connects to server and uploads all the data
	 */
	public void run() {
		try {
			Socket clientSocket = new Socket("sun01.cise.ufl.edu",5978);
			DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
			BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			String code = "UPLOAD";
			String response = null;
			outToServer.writeBytes(code + '\n');
			response = inFromServer.readLine();
			outToServer.writeBytes(email + '\n');
			response = inFromServer.readLine();
			outToServer.writeBytes(pword + '\n');
			response = inFromServer.readLine();
			if (response.equals("ACCEPTED")) {
				it = values.iterator();
			while (it.hasNext()) {
				dbPackage current = (dbPackage) it.next();
				outToServer.writeBytes(current.toString() + '\n');
				response = inFromServer.readLine();
			}
			outToServer.writeBytes("DONE" + '\n');
			ac.runOnUiThread(new Runnable() {
			    public void run() {
			        Toast t = Toast.makeText(ac, "Upload Completed", Toast.LENGTH_LONG);
			        t.setGravity(Gravity.CENTER, 0, 0);
			        t.show();
			    }
			});
			}
			else {
				ac.runOnUiThread(new Runnable() {
				    public void run() {
				    	Toast t = Toast.makeText(ac, "Invalid Password", Toast.LENGTH_LONG);
				    	t.setGravity(Gravity.CENTER, 0, 0);
				    	t.show();
				    }
				});
				//outToServer.writeBytes("DONE" + '\n');
			}
			clientSocket.close();
			
		} catch (UnknownHostException e) {
			ac.runOnUiThread(new Runnable() {
			    public void run() {
			    	Toast t = Toast.makeText(ac, "Internet Access Required", Toast.LENGTH_LONG);
			    	t.setGravity(Gravity.CENTER, 0, 0);
			    	t.show();
			    }
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}

/**
 * Class that handles downloaded user data from the external server
 * @author Sean
 *
 */
class ClientImportThread implements Runnable {
	public void run() {
		try {
			Socket clientSocket = new Socket("sun01.cise.ufl.edu",5978);
			String code = "IMPORT";
			String response = null;
			DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
			BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			outToServer.writeBytes(code + '\n');
			while (!response.equals("DONE")) {
				response = inFromServer.readLine();
				outToServer.writeBytes("OK" + '\n');
			}
			clientSocket.close();
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
}



